package com.example.dajian_hou.controller;

import com.example.dajian_hou.common.Result;
import com.example.dajian_hou.entity.User;
import com.example.dajian_hou.service.UserService;
import com.example.dajian_hou.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        if (username == null || password == null) {
            return Result.error("用户名和密码不能为空");
        }
        User user = userService.login(username, password);
        if (user != null) {
            // 生成token
            String token = jwtUtils.generateToken(user.getId(), user.getUsername());
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            
            return Result.success(data);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    @GetMapping("/list")
    public Result<List<User>> list() {
        List<User> users = userService.findAll();
        return Result.success(users);
    }

    @GetMapping("/page")
    public Result<Map<String, Object>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            Map<String, Object> result = userService.findByPage(pageNum, pageSize, keyword);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取用户列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/save")
    public Result<Void> save(@RequestBody User user) {
        try {
            userService.save(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error("保存用户失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    public Result<Void> update(@RequestBody User user) {
        try {
            userService.update(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新用户失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        try {
            userService.deleteById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除用户失败：" + e.getMessage());
        }
    }

    @PostMapping("/batch-delete")
    public Result<Void> batchDelete(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的用户");
            }
            userService.deleteByIds(ids);
            return Result.success();
        } catch (Exception e) {
            return Result.error("批量删除用户失败：" + e.getMessage());
        }
    }

    @PostMapping("/update-password")
    public Result<Void> updatePassword(@RequestBody Map<String, String> passwordForm, @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            String oldPassword = passwordForm.get("oldPassword");
            String newPassword = passwordForm.get("newPassword");
            
            if (oldPassword == null || newPassword == null) {
                return Result.error("原密码和新密码不能为空");
            }
            
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未登录或token无效");
            }

            // 从token中获取用户ID
            String actualToken = token.substring(7);
            if (!jwtUtils.validateToken(actualToken)) {
                return Result.error("token已过期");
            }

            Long userId = jwtUtils.getUserIdFromToken(actualToken);
            User currentUser = userService.findById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }
            
            // 验证原密码
            if (!userService.verifyPassword(currentUser.getId(), oldPassword)) {
                return Result.error("原密码错误");
            }
            
            // 更新密码
            userService.updatePassword(currentUser.getId(), newPassword);
            return Result.success();
        } catch (Exception e) {
            return Result.error("修改密码失败：" + e.getMessage());
        }
    }

    @PutMapping("/update-info")
    public Result<Void> updateUserInfo(@RequestBody User user, @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error("未登录或token无效");
            }

            // 从token中获取用户ID
            String actualToken = token.substring(7);
            if (!jwtUtils.validateToken(actualToken)) {
                return Result.error("token已过期");
            }

            Long userId = jwtUtils.getUserIdFromToken(actualToken);
            User currentUser = userService.findById(userId);
            if (currentUser == null) {
                return Result.error("用户不存在");
            }

            // 更新用户信息，保持密码不变
            user.setId(userId); // Ensure we are updating the correct user
            userService.updateUserInfo(user);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新用户信息失败：" + e.getMessage());
        }
    }
}
